import React from 'react';
import TMainBasePage from '@/base/TMainBasePage';
import { DatePicker, Anchor, Tooltip, Spin } from 'antd';
import { connect } from 'umi';
import { StickyContainer, Sticky } from 'react-sticky';
import { getBusinessMenus } from '@/services/businessAnalysis';
import moment from 'moment';
import { HttpCode } from '#/utils/contacts.js';
import Security from './components/Security';
import Operate from './Operate';
import Management from './Management';
import Transaction from './Transaction';
import ElectricitySales from './Electricity';
import { getStartAndEndDate, getDisabledDate, getPageConent } from './helper';
import { getDictionaryValue } from '@/services/common';
import { getOperationDate } from './service';
import styles from './index.less';

const { Link } = Anchor;

const MockExtra = {
  week: { title: '周报', format: '第wo' },
  month: { title: '月报', format: 'MM月' },
  year: { title: '年报', format: 'YYYY年' },
};

const TAB_SECURITY = 'Security';

const Components = {
  Security,
  Management,
  Operate,
  Transaction,
  ElectricitySales,
};

const DEFAULT_DATE = moment().add(-1, 'd');

export const { Provider, Consumer } = React.createContext(null);
@connect(({ global }) => ({
  menuCode: global.configure.menuCode,
}))
export default class BusinessAnalysis extends TMainBasePage {
  constructor(props) {
    super(props);
    this.state.pageMenuList = []; //页面导航菜单
    this.state.chooseDate = DEFAULT_DATE;
    this.state.type = 'month';
    this.state.activeTab = `#${TAB_SECURITY}`;
    this.state.pickerProps = {};
    this.state.spinLoding = true;
    this.state.errorMessage = '';
    this.state.dateObj = getStartAndEndDate(DEFAULT_DATE, this.state.type);
    this.state.pageConfig = { menuArray: [], pageArray: [] };
    this._isSpinLoading_ = true;
    this.state.errorMsg = 'error';
    this.state.updateData = {};
    this.state.dateBody = {};
  }
  anchorRef = React.createRef();

  async componentDidMount() {
    const { type } = this.state;
    this._onGetStation(); //中心
    this.setState({
      pickerProps: {
        picker: type,
        format: MockExtra[type].format,
      },
    });

    await this.getTabMenu();
    await this.fetchData();
    await this.fetchUpdateDate();
  }

  componentDidUpdate() {}

  getTabMenu = async () => {
    const { type } = this.state;

    const response = await getBusinessMenus(this.props.menuCode);
    if (response && response.statusCode == HttpCode.SUCCESS) {
      const { pageMenuList } = response;
      this.setState({
        pageMenuList,
      });
      const configPage = getPageConent(pageMenuList, type);

      this.setState({
        pageConfig: configPage,
        spinLoding: false,
        errorMsg: '',
      });
      setTimeout(() => {
        this.anchorRef.current && this.anchorRef.current.setCurrentActiveLink(`#${TAB_SECURITY}`);
      }, 10);
    } else {
      this.setState({
        errorMsg: 'error',
      });
    }
  };

  _onHandleType = (key) => {
    const configPage = getPageConent(this.state.pageMenuList, key);
    this.anchorRef.current && this.anchorRef.current.handleScrollTo(`#${TAB_SECURITY}`);

    this.setState({
      type: key,
      dateObj: getStartAndEndDate(DEFAULT_DATE, key),
      chooseDate: DEFAULT_DATE,
      pageConfig: configPage,
      pickerProps: {
        picker: key,
        format: MockExtra[key].format,
      },
    });
  };

  handleChange = (date) => {
    const { type } = this.state;
    const data = getStartAndEndDate(date, type);
    this.setState({
      chooseDate: date,
      dateObj: data,
    });
  };

  //Anchor组件方法
  handleAnchorClick = (e, link) => {
    e.preventDefault();
    if (link.href) {
      let element = document.getElementById(link.href);
      element && element.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
  };

  handleAnchorChange = (currentActiveLink) => {
    this.setState({
      activeTab: currentActiveLink,
    });
  };

  _disabledDate(current) {
    if (current) {
      return (
        current < moment('2019-12-31').subtract(1, 'days') ||
        current > getDisabledDate(this.state.type)
      );
    }
    return false;
  }

  fetchData = async () => {
    let res = await getDictionaryValue('BPFT');
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const { dictionaryValueBodies } = res;
      const updateData = {};
      dictionaryValueBodies.map((item) => {
        let [user, method, updateDate] = item.description.split('，');
        updateData[item.value] = { user, method, updateDate };
      });
      this.setState({ updateData });
    }
  };
  fetchUpdateDate = async () => {
    let res = await getOperationDate();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const { dateBody } = res;
      this.setState({ dateBody });
    }
  };

  onPickerWithType(type, chooseDate, pickerProps) {
    const pops = {
      bordered: false,
      value: chooseDate,
      defaultValue: moment(),
      allowClear: false,
      disabledDate: this._disabledDate.bind(this),
      onChange: this.handleChange.bind(this),
      inputReadOnly: true,
    };
    return <DatePicker {...pops} {...pickerProps} mode={type} />;
  }

  //头部右侧日期切换 周报 月报 年报
  HeaderExtraRender = () => {
    const { chooseDate, type, pickerProps } = this.state;
    return (
      <div className={styles.headerExtra}>
        <div className={styles.left}>
          {Object.entries(MockExtra).map(([key, item]) => (
            <span
              key={key}
              value={key}
              className={type === key ? styles.active : undefined}
              onClick={this._onHandleType.bind(this, key)}
            >
              {item.title}
            </span>
          ))}
        </div>
        <div className={styles.right}>{this.onPickerWithType(type, chooseDate, pickerProps)}</div>
      </div>
    );
  };

  //动态生成模块组件
  renderModulesName = (key, title) => {
    const { dateObj, type } = this.state;
    const code = key.charAt(0).toUpperCase() + key.slice(1);
    const MouduleComponents = Components[code];

    const props = {
      title,
      dateObj, //startDate, endDate
      type, //日期类型
      code,
    };
    return (
      <div id={code} key={code}>
        <MouduleComponents {...props} />
      </div>
    );
  };

  render() {
    const {
      pageConfig: { pageArray, menuArray, PAGE_CONTENT_KEY },
      pageMenuList,
      activeTab,
      spinLoding,
      updateData,
      dateBody,
    } = this.state;
    if (spinLoding && pageMenuList.length === 0) {
      return this._onLoadingRender(false);
    }
    if (!spinLoding && this.state.errorMsg.length > 0) {
      return this._onEmptyRender();
    }
    if (this.state.errorMsg.length > 0) {
      return this._onErrorRender();
    }

    return (
      <Spin spinning={spinLoding}>
        <div className={styles.containerWrap}>
          <StickyContainer>
            <Sticky>
              {({ style }) => (
                <header className={styles.headerWrap} style={{ ...style, height: 74 }}>
                  <Anchor
                    onClick={this.handleAnchorClick.bind(this)}
                    onChange={this.handleAnchorChange.bind(this)}
                    targetOffset={110}
                    ref={this.anchorRef}
                  >
                    {pageMenuList.map((item, index) => {
                      const {
                        root: { menuName, menuCode },
                      } = item;
                      const code = menuCode.charAt(0).toUpperCase() + menuCode.slice(1);
                      return (
                        <Tooltip
                          key={index}
                          overlayClassName="overtoop"
                          placement="bottomLeft"
                          title={
                            !menuArray.includes(menuCode) &&
                            menuCode == 'management' &&
                            '经营内容只在月报、年报中展示'
                          }
                        >
                          {!menuArray.includes(menuCode) ? (
                            <span
                              style={{
                                fontSize: 18,
                                color: '#acb1c1',
                                cursor: 'pointer',
                                height: 40,
                                lineHeight: '70px',
                                margin: '0 70px 0 10px',
                              }}
                            >
                              {menuName}
                            </span>
                          ) : (
                            <Link
                              href={`#${code}`}
                              title={<span>{menuName}</span>}
                              key={code}
                              className={
                                !menuArray.includes(menuCode) ? styles.linkDisable : undefined
                              }
                            >
                              {activeTab == `#${code}` && menuArray.includes(menuCode) && (
                                <span
                                  style={{
                                    width: 16,
                                    height: 3,
                                    display: 'inline-block',
                                    background: '#1E7CE8',
                                    marginLeft: 20,
                                  }}
                                  className={style.spanLine}
                                />
                              )}
                            </Link>
                          )}
                        </Tooltip>
                      );
                    })}
                  </Anchor>
                  {this.HeaderExtraRender()}
                </header>
              )}
            </Sticky>

            <div className={styles.content}>
              {/* 安全=>Security  经营=>Management  运营=>Operate  交易=>Transaction*/}
              {pageArray.map((item) => {
                const {
                  root: { menuName, menuCode },
                } = item;
                return (
                  <Provider
                    value={{ menuCode, key: PAGE_CONTENT_KEY[menuCode], updateData, dateBody }}
                    key={menuCode}
                  >
                    {this.renderModulesName(menuCode, menuName)}
                  </Provider>
                );
              })}
            </div>
          </StickyContainer>
        </div>
      </Spin>
    );
  }
}
